package com.topInterview;

/**
 * @Author: huangzhigao
 * @Date: 2022/2/13 12:54
 */
public class Leetcode7_StringToInteger {
    public int myAtoi(String s) {
        if (s == null || s.length() < 1) {
            return 0;
        }
        String res = removedZeroAndInValidStr(s.trim());

        if (res == null || res.equals("")) {
            return 0;
        }


        char[] chars = res.toCharArray();
        if (!isValid(chars)) {
            return 0;
        }
        //符号位是否为负数
        boolean posi = chars[0] == '-';
        int minq = Integer.MIN_VALUE / 10;
        int minr = Integer.MIN_VALUE % 10;
        int ans = 0;
        int cur = 0;
        for (int i = (chars[0] == '+' || chars[0] == '-') ? 1 : 0; i < chars.length; i++) {
            cur = '0' - chars[i];
            if (ans < minq || (ans == minq && cur < minr)) {
                return posi ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
            ans = ans * 10 + cur;
        }

        //如果是正数，且ans为最小值，则返回最大值
        if (!posi && ans == Integer.MIN_VALUE) {
            return Integer.MAX_VALUE;
        }

        return posi ? -ans : ans;
    }


    public boolean isValid(char[] chars) {
        if (chars[0] != '-' && chars[0] != '+' && (chars[0] < '0' || chars[0] > '9')) {
            return false;
        }

        if ((chars[0] == '-' || chars[0] == '+') && chars.length < 2) {
            return false;
        }

        for (int i = 1; i < chars.length; i++) {
            if (chars[i] < '0' || chars[i] > '9') {
                return false;
            }
        }
        return true;
    }


    public String removedZeroAndInValidStr(String str) {
        boolean sign = str.startsWith("+") || str.startsWith("-");
        //start来到不是0的位置
        int start = sign ? 1 : 0;
        char[] chars = str.toCharArray();

        for (; start < chars.length; start++) {
            if (chars[start] != '0') {
                break;
            }
        }

        //end为来到最后一位不是数字的位置
        int end = -1;

        for (int j = chars.length - 1; j >= (sign ? 1 : 0); j--) {
            if (chars[j] < '0' || chars[j] > '9') {
                end = j;
            }
        }

        String firstChar = sign ? String.valueOf(str.charAt(0)) : "";
        //如果end为-1，则从start一直切分到字符串末尾
        return firstChar + str.substring(start, end == -1 ? str.length() : end);
    }

    public static void main(String[] args) {
        Leetcode7_StringToInteger s = new Leetcode7_StringToInteger();
        s.myAtoi("42");
    }
}
